#!/bin/bash

# 设置镜像名称变量，便于维护
IMAGE_NAME="crpi-vf9r4pco4gkrumg9.cn-shanghai.personal.cr.aliyuncs.com/keeng_image/manga:latest"

# 删除旧镜像（如果存在）
echo "在本地删除旧镜像..."
docker rmi ${IMAGE_NAME} 2> /dev/null || echo "旧镜像不存在，继续执行..."

# 使用Dockerfile构建新镜像
echo "在本地构建新镜像..."
docker build -t ${IMAGE_NAME} .

# 推送镜像到镜像仓库
echo "本地向阿里云镜像仓库推送镜像..."
docker push ${IMAGE_NAME}


SERVER_IP="117.72.166.8"
USERNAME="root"

echo "在远程服务器上部署新镜像..."
# 远程执行部署命令
ssh ${USERNAME}@${SERVER_IP} << 'EOF'

  IMAGE_NAME="crpi-vf9r4pco4gkrumg9.cn-shanghai.personal.cr.aliyuncs.com/keeng_image/manga:latest"

  echo "在远程服务器上拉取镜像..."
  docker pull $IMAGE_NAME

  echo "清除被覆盖的镜像"
  docker image prune -f

  echo "停止并删除旧容器..."
  docker stop manga || true  # 忽略不存在的容器错误
  docker rm manga || true


  echo "启动新容器..."
  docker run -d \
    --name manga \
    -p 8080:8080 \
    $IMAGE_NAME
EOF

echo "✅-部署完成"